from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db import DatabaseError
from django.http import HttpResponseBadRequest
from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse
from django.views import View

from apps.users.models import Users


class Register(View):
    """ the world need register！！"""

    def get(self, request):

        return render(request, 'register.html')

    def post(self, request):

        username = request.POST.get('user')
        password = request.POST.get('password')

        # try:
        #
        #     if Users.objects.filter(username=username).count()>=1:
        #         pass
        # except:
        #     pass
        # else:
        #     return HttpResponseBadRequest('该用户名已被注册')

        try:
            Users.objects.get(username=username)
        except:

            try:
                user = Users.objects.create_user(username=username, password=password)
            except DatabaseError:
                return HttpResponseBadRequest('注册失败')

            # hold on the login status
            login(request, user)

            response = redirect(reverse('index:index'))

            response.set_cookie('username', user.username, max_age=3600 * 24 * 15)

            return response
        else:

            return HttpResponseBadRequest('用户名已经存在')


class Login(View):
    """need login too"""

    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        username = request.POST.get('user').encode('utf-8')
        password = request.POST.get('password')
        print(username,password)
        try:
            user = authenticate(username=username, password=password)
        except:
            return HttpResponseBadRequest('登录错误，请重试')

        if user:
            login(request, user)
        else:
            return HttpResponseBadRequest('登录错误(maybe_redis_error?)，请重试')

        next = request.GET.get('next')
        if next:
            response = redirect(next)
        else:
            response = redirect((reverse('index:index')))
        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)

        return response


class Logout(View):
    def get(self, request):
        # logout
        logout(request)

        response = redirect(reverse('index:index'))

        # 退出登录时清除cookie中的username
        response.delete_cookie('username')

        return response


class Alterpassword(LoginRequiredMixin, View):
    """change password"""

    def get(self, request):

        return render(request, 'changepassword.html')

    def post(self, request):
        original_password = request.POST.get('original_password')
        new_password = request.POST.get('new_password')
        new_password2 = request.POST.get('new_password2')

        if new_password != new_password2:
            return HttpResponseBadRequest('两次输入的密码不一致')

        if not request.user.check_password(original_password):
            return  HttpResponseBadRequest('原始密码错误')

        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:
            return   HttpResponseBadRequest('修改密码失败')

        logout(request)

        response = redirect(reverse('users:login'))

        response.delete_cookie('username')

        return response
